package com.woniuxy.flowable.task;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.woniuxy.flowable.feign.CustomerFeign;
import com.woniuxy.flowable.util.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.JavaDelegate;
import org.springframework.stereotype.Component;

/**
 * 客户审批流程任务处理器
 * @author woniuxy
 */
@Slf4j
@Component

public class CustomerApprovalHandler implements JavaDelegate {
    private CustomerFeign customerFeign;
    
    @Override
    public void execute(DelegateExecution execution) {
        try {
            // 确保 customerFeign 被正确注入
            if (customerFeign == null) {
                try {
                    customerFeign = SpringUtils.getBean(CustomerFeign.class);
                    log.info("通过SpringUtils获取CustomerFeign实例成功");
                } catch (Exception e) {
                    log.error("通过SpringUtils获取CustomerFeign实例失败: {}", e.getMessage());
                    throw new RuntimeException("无法获取CustomerFeign实例: " + e.getMessage());
                }
            }
            
            String taskName = execution.getCurrentActivityId();
            String processInstanceId = execution.getProcessInstanceId();
            String businessKey = execution.getProcessInstanceBusinessKey();
            
            log.info("执行客户审批任务，任务名称: {}, 流程实例ID: {}, 业务Key: {}", 
                taskName, processInstanceId, businessKey);
            
            // 根据任务名称执行不同的处理逻辑
            if ("taskSuccess".equals(taskName)) {
                handleSuccess(execution);
            } else if ("taskFail".equals(taskName)) {
                handleFail(execution);
            }
            
        } catch (Exception e) {
            log.error("执行客户审批任务失败", e);
            throw new RuntimeException("执行客户审批任务失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 处理审批成功
     */
    private void handleSuccess(DelegateExecution execution) {
        try {
            String businessKey = execution.getProcessInstanceBusinessKey();
            String processInstanceId = execution.getProcessInstanceId();
            
            // 参数验证
            if (businessKey == null || businessKey.trim().isEmpty()) {
                log.error("业务Key为空，无法处理审批成功");
                throw new RuntimeException("业务Key为空");
            }
            
            if (processInstanceId == null || processInstanceId.trim().isEmpty()) {
                log.error("流程实例ID为空，无法处理审批成功");
                throw new RuntimeException("流程实例ID为空");
            }
            
            // 确保 customerFeign 不为空
            if (customerFeign == null) {
                log.error("CustomerFeign实例为空，无法调用客户管理服务");
                throw new RuntimeException("CustomerFeign实例为空");
            }
            
            Long customerId = Long.valueOf(businessKey);
            
            // 生成客户代码（使用雪花ID）
            String customerCode = generateCustomerCode();
            log.info("生成客户代码: {}", customerCode);
            
            // 调用客户管理服务更新客户状态
            log.info("开始调用客户管理服务，流程实例ID: {}, 客户代码: {}", processInstanceId, customerCode);
            customerFeign.handleApproveSuccess(processInstanceId, customerCode);
            
            log.info("客户审批成功处理完成，客户ID: {}, 客户代码: {}", customerId, customerCode);
            
        } catch (NumberFormatException e) {
            log.error("业务Key格式错误，无法转换为Long类型: {}", execution.getProcessInstanceBusinessKey(), e);
            throw new RuntimeException("业务Key格式错误: " + e.getMessage(), e);
        } catch (Exception e) {
            log.error("处理客户审批成功失败，流程实例ID: {}, 业务Key: {}", 
                execution.getProcessInstanceId(), execution.getProcessInstanceBusinessKey(), e);
            throw new RuntimeException("处理审批成功失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 处理审批失败
     */
    private void handleFail(DelegateExecution execution) {
//        try {
//            String businessKey = execution.getProcessInstanceBusinessKey();
//            Long customerId = Long.valueOf(businessKey);
//
//            // 获取拒绝原因
//            String rejectReason = (String) execution.getVariable("rejectReason");
//            if (rejectReason == null) {
//                rejectReason = "审批未通过";
//            }
//
//            // 调用客户管理服务更新客户状态
//            Map<String, Object> updateData = new HashMap<>();
//            updateData.put("customerId", customerId);
//            updateData.put("approvalStatus", "REJECTED");
//            updateData.put("rejectReason", rejectReason);
//            updateData.put("processInstanceId", execution.getProcessInstanceId());
//
//            // 发送HTTP请求到客户管理服务
//            String callbackUrl = "http://localhost:8001/api/customers/callback";
//            sendCallback(callbackUrl, updateData);
//
//            log.info("客户审批失败处理完成，客户ID: {}, 拒绝原因: {}", customerId, rejectReason);
//
//        } catch (Exception e) {
//            log.error("处理客户审批失败", e);
//            throw new RuntimeException("处理审批失败: " + e.getMessage(), e);
//        }
    }
    
    /**
     * 生成客户代码（使用雪花ID）
     */
    private String generateCustomerCode() {
        // 这里可以使用雪花ID算法生成唯一客户代码
        return IdUtil.getSnowflakeNextIdStr();
    }
    
}
